Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Amazon Hard Problems
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Count All Valid Pickup and Delivery Options

Problem Statement

You are given a positive integer n, representing total orders where each order consists of a pickup and a delivery service.

Count all valid pickup/delivery sequences such that delivery(x) is always after of pickup(x).

Return the answer modulo 10^9 + 7.

Examples

  • Example 1:

    • Input: n = 1
    • Expected Output: 1
    • Justification: With just one order, there's only one valid sequence: pickup and then delivery. Thus, the expected output is 1.
  • Example 2:

    • Input: n = 2
    • Expected Output: 6
    • Justification: With two orders, there are six valid sequences: P1 D1 P2 D2, P1 P2 D1 D2, P1 P2 D2 D1, P2 D2 P1 D1, P2 P1 D1 D2, P2 P1 D2 D1. Therefore, the expected output is 6.
  • Example 3:

    • Input: n = 5
    • Expected Output: 113400
    • Justification: For five orders, the number of valid sequences increases significantly because each additional order adds complexity to how pickups and deliveries can be arranged. The expected output for three orders is 113400.

Solution

To solve this problem, we'll use a dynamic programming approach. This method is chosen because it allows us to build the solution for n orders based on the solutions for fewer orders, thus reducing the overall computational complexity. The key insight is to recognize that for each new order, we can insert its pickup and delivery actions into the sequences generated for the previous orders in a specific number of ways. Specifically, when adding the nth order, we can insert its pickup anywhere in the sequence of the previous n-1 orders, and its delivery can then be placed in any position following its pickup. This results in a pattern where the number of sequences grows significantly with each additional order, but each step can be calculated from the previous one.

The effectiveness of this approach lies in its ability to break down the problem into smaller, manageable pieces, leveraging the fact that the solution for n orders is built upon the solution for n-1 orders. By systematically expanding our calculation with each additional order, we ensure that all valid sequences are counted without redundant computations or overlooking any possibilities.

Step-by-Step Algorithm

  1. Initialization:

    • Declare a MOD constant with the value of (10^9 + 7) to handle large numbers during calculations.
    • Initialize a long variable count to 1. This variable will hold the cumulative result of the calculations for the number of valid sequences.
  2. Loop Through Orders:

    • Iterate from 1 through n (inclusive), with i representing the current order number. This loop calculates the cumulative number of valid sequences for each order.
      • For each i:
        • First, update count to account for the new combinations introduced by the addition of the ith pickup. Multiply count by i and apply the modulo MOD to ensure the result stays within bounds. This step accounts for the different permutations of the orders themselves.
        • Next, update count again to incorporate the positions where the ith delivery can be inserted. Multiply count by (2 * i - 1) and apply the modulo MOD. This step considers the specific requirement that each delivery follows its corresponding pickup and calculates the number of ways the delivery can be positioned in relation to the pickups and other deliveries already considered.
  3. Finalize and Return Result:

    • The loop concludes with count holding the total number of valid sequences, modulo (10^9 + 7).
    • Cast count to an int (as per the method's return type) and return it.

Algorithm Walkthrough

Let's consider the Input: n = 5

  • Initialization:

    • MOD is set to (10^9 + 7).
    • count is initialized to 1.
  • Loop Through Orders:

    • For i = 1:
      • Multiply count by i (1), count = 1.
      • Multiply count by (2*1 - 1) (1), count = 1.
    • For i = 2:
      • Multiply count by i (2), count = 2.
      • Multiply count by (2*2 - 1) (3), count = 6.
    • For i = 3:
      • Multiply count by i (3), count = 18.
      • Multiply count by (2*3 - 1) (5), count = 90.
    • For i = 4:
      • Multiply count by i (4), count = 360.
      • Multiply count by (2*4 - 1) (7), count = 2520.
    • For i = 5:
      • Multiply count by i (5), count = 12600.
      • Multiply count by (2*5 - 1) (9), count = 113400.
  • Finalize and Return Result:

    • At the end of the loop, count equals 113400.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  • : The primary operation in the algorithm is a loop that runs n times, where n is the number of orders. Within this loop, we perform a constant number of mathematical operations (multiplications and modulo operations), which do not depend on the size of n beyond the loop's iteration. Therefore, the overall time complexity is linear with respect to the input size.

Space Complexity

  • : Our algorithm uses a fixed amount of space regardless of the input size. The variables used to calculate the count of valid sequences (including the MOD constant and loop counter) do not scale with n. Thus, the space complexity is constant.
Count All Valid Pickup and Delivery Options (hard)
Length of the Longest Valid Substring (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity